package com.shwread.android.qysw.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.shwread.android.qysw10000243.R;

import java.util.ArrayList;
import java.util.List;

import logic.lbs.PoiOverlay;

/**
 * 因公外出申请拜访客户地址map
 */

public class VisitViewMapActivity extends FragmentActivity implements
        AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, LocationSource,
        AMapLocationListener, AMap.OnMapLoadedListener,
        AMap.OnMapClickListener {
    private AMap aMap;
    private AutoCompleteTextView searchText;// 输入搜索关键字
    private String keyWord = "";// 要输入的poi搜索关键字
    private ProgressDialog progDialog = null;// 搜索时进度条
    private AMapLocation location;
    private List<PoiItem> poiItems;
    private PoiResult poiResult;

    private OnLocationChangedListener mListener;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    private String city = "";
    private PoiItem poiItem;
    private ImageView img_back;
    private TextView sure_textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_visit_view_map);
       /* if (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION},
                        1000);//自定义的code
            }
        }*/
        img_back= (ImageView) findViewById(R.id.img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        sure_textView= (TextView) findViewById(R.id.sure_textView);
        sure_textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        init();
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            searchText = (AutoCompleteTextView) findViewById(R.id.keyWord);
            aMap.setOnMarkerClickListener(this);// 添加点击marker监听事件
            aMap.setInfoWindowAdapter(this);// 添加显示infowindow监听事件
            aMap.setOnMapLoadedListener(this);
            aMap.setOnMapClickListener(this);

            aMap.setLocationSource(this);
            MyLocationStyle myLocationStyle = new MyLocationStyle();
            myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable
                    .location_default_gps));// 设置小蓝点的图标
            myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
            myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
            aMap.setMyLocationStyle(myLocationStyle);
            aMap.moveCamera(CameraUpdateFactory.zoomTo(17)); //缩放比例

            //设置amap的属性
            UiSettings settings = aMap.getUiSettings();
            settings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
            aMap.setMyLocationEnabled(true);//
        }

        searchText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(city)) {
                    Toast.makeText(VisitViewMapActivity.this, "定位失败，请稍后重试", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent = new Intent(VisitViewMapActivity.this, SearchLocationsActivity.class);
                    intent.putExtra("city", city);
                    intent.putExtra("lat", location.getLatitude());
                    intent.putExtra("lon", location.getLongitude());
                    startActivityForResult(intent, 1000);

                }
            }
        });
        showProgressDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1000 && resultCode == 1001) {
            poiItems = new ArrayList<>();
            poiItem = (PoiItem) data.getParcelableExtra("result");
            poiItems.clear();
            poiItems.add(poiItem);
            ArrayList<Marker> markers = new ArrayList();
            aMap.clear();// 清理之前的图标
            PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
            poiOverlay.removeFromMap();
            PoiItem pMy = new PoiItem("", new LatLonPoint(data.getDoubleExtra("lat", 0), data
                    .getDoubleExtra("lon", 0)), "", "");
            poiItems.add(pMy);
            for (int var1 = 0; var1 < poiItems.size(); ++var1) {
                MarkerOptions options = null;
                if (var1 == 0) {
                    options = (new MarkerOptions()).position(new LatLng((
                            poiItems.get(var1)).getLatLonPoint().getLatitude(), (poiItems
                            .get(var1)).getLatLonPoint().getLongitude())).title((poiItems
                            .get(var1)).getTitle()).snippet((poiItems.get(var1))
                            .getSnippet()).icon(BitmapDescriptorFactory.fromResource(R.drawable
                            .mark));
                } else {
                    options = (new MarkerOptions()).position(new LatLng(data.getDoubleExtra("lat", 0), data
                            .getDoubleExtra("lon", 0)))
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable
                                    .location_default_gps));
                }
                Marker var2 = aMap.addMarker(options);
                var2.setObject(Integer.valueOf(var1));
                markers.add(var2);
            }
            LatLngBounds var1 = getLatLng(poiItems);
            aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(var1, 200));
//            poiOverlay.zoomToSpan();
        }
    }

    private LatLngBounds getLatLng(List<PoiItem> a) {
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        for(int var2 = 0; var2 < a.size(); ++var2) {
            var1.include(new LatLng(((PoiItem)a.get(var2)).getLatLonPoint().getLatitude(), ((PoiItem)a.get(var2)).getLatLonPoint().getLongitude()));
        }
        return var1.build();
    }

    /**
     * 显示进度框
     */
    private void showProgressDialog() {
        if (progDialog == null)
            progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setIndeterminate(false);
        progDialog.setCancelable(false);
        progDialog.setMessage("正在定位:\n" + keyWord);
        progDialog.show();
    }

    /**
     * 隐藏进度框
     */
    private void dissmissProgressDialog() {
        if (progDialog != null) {
            progDialog.dismiss();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        aMap.animateCamera(CameraUpdateFactory.changeLatLng(new LatLng(
                marker.getPosition().latitude, marker.getPosition().longitude)), 500, new AMap
                .CancelableCallback() {


            @Override
            public void onFinish() {

            }

            @Override
            public void onCancel() {

            }
        });
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
        }
        return true;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(final Marker marker) {
        View view = getLayoutInflater().inflate(R.layout.poikeywordsearch_uri, null);
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(marker.getTitle());

        TextView snippet = (TextView) view.findViewById(R.id.snippet);
        snippet.setText("（"+city+marker.getSnippet()+"）");
        return view;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        dissmissProgressDialog();
        location = aMapLocation;
        city = location.getCity();
        Log.e("详细地址",location.getAddress());
        if (mListener != null && location != null) {
            if (location != null && location.getErrorCode() == 0) {
                mListener.onLocationChanged(location);// 显示系统箭头
                mLocationClient.stopLocation();
            }
        } else {
            Toast.makeText(VisitViewMapActivity.this, "定位失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000 * 10);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public void onMapLoaded() {

    }
}
